<template>
    <view class="portrait">
        <view class="portrait-steps">
            <text class="portrait-title">上传照片</text>
            <text class="portrait-info">请上传一张清晰的正面照片</text>
            <uv-steps current="1" activeColor="#FD3523" inactiveColor="#E2E2E2" @click="handleSteps">
                <uv-steps-item title="证件上传"></uv-steps-item>
                <uv-steps-item title="照片上传"></uv-steps-item>
            </uv-steps>
        </view>

        <view class="portrait-card">
            <text class="portrait-title2">上传照片</text>
            <view class="portrait-upload">
                <view class="image-wrapper">
                    <image :src="portrait_img" mode="aspectFit" class="portrait-image"></image>
                    <view class="image-actions">
                        <view class="action-btn" @click="previewImage">
                            <text class="iconfont icon-fangdajing"></text>
                        </view>
                        <view class="action-btn" @click="handleCamera">
                            <text class="iconfont icon-shangchuan"></text>
                        </view>
                    </view>
                </view>
            </view>
            <view class="portrait-tips">
                <text class="tips-title">照片要求：</text>
                <text class="tips-item">1. 近期照片</text>
                <text class="tips-item">2. 照片清晰，五官可见，着装得体</text>
                <text class="tips-item">3. 背景为纯色，建议使用白色背景</text>
                <text class="tips-item">4. 照片大小不超过2MB</text>
                <text class="tips-item">5. 不要戴耳机，戴帽子</text>
            </view>
        </view>

        <view class="next-button">
            <uv-button iconColor="#FD3523" color="#FD3523" :plain="false" @click="handleNext"
                :disabled="!portrait_img">完成</uv-button>
        </view>
        <uv-loading-page :loading="imgLoading" bgColor="#b1b1b173" color="#000" loading-text="图片上传中..." font-size="32rpx"></uv-loading-page>
    </view>
</template>

<script>
import { putUserUpdate } from '@/http/user.js'

export default {
    data() {
        return {
            portrait_img: "../../static/img/portrait.png",
            token: '',
            userinfo: {},
            orderId: "",
            imgLoading: false
        }
    },
    onLoad(options) {
        console.log(options, 'options');
        
        this.orderId = options.orderId || ''
        // 监听相机拍照结果
        uni.$on('getImage', async res => {
            try {

                const result = await this.uploadFilePromise(res.data)
                if (result) {
                    this.portrait_img = result
                    uni.showToast({
                        title: '图片处理成功',
                        icon: 'success'
                    })
                }
            } catch (err) {
                console.error('上传失败:', err)
                uni.showToast({
                    title: '上传失败',
                    icon: 'error'
                })
            } finally {
                // uni.hideLoading()
            }
        })
        this.userinfo = uni.getStorageSync('userinfo')
        this.portrait_img = this.userinfo.avatar || '../../static/img/portrait.png'
    },
    methods: {
        handleCamera() {
            uni.showModal({
                title: '拍照提示',
                content: '请穿好衣服在光线充足,背景简单的环境下拍摄',
                showCancel: false,
                confirmText: '我知道了',
                success: ({ confirm, cancel }) => {
                    if (confirm) {
                        uni.navigateTo({
                            url: '/pages/profile/camera?coverImageType=portrait'
                        })
                    }
                }
            })
        },
        previewImage() {
            if (!this.portrait_img || this.portrait_img.includes('portrait')) {
                return uni.showToast({
                    title: '暂无图片',
                    icon: 'none'
                })
            }
            uni.previewImage({
                urls: [this.portrait_img],
                current: 0
            })
        },
        // 普通图片上传
        uploadFilePromise(fileData) {
            this.token = uni.getStorageSync('token')
            return new Promise((resolve, reject) => {
                // 检查图片尺寸
                uni.getImageInfo({
                    src: fileData,
                    success: async (imageInfo) => {
                        if (imageInfo.width > 2400 || imageInfo.height > 2400) {
                            uni.showToast({
                                title: '图片尺寸不能超过2400像素',
                                icon: 'none'
                            })
                            reject(new Error('图片尺寸过大'))
                            return
                        }
                        this.imgLoading = true
                        uni.showLoading({
                            title: '上传中',
                            mask: true
                        })
                        try {
                            // 压缩图片
                            const compressedImage = await this.compressImage(fileData)

                            // 上传到OSS
                            const ossUrl = await this.uploadToOSS(compressedImage)

                            // 调用证件照API
                            const portraitUrl = await this.createPortrait(ossUrl)

                            // 将证件照再次上传到OSS
                            const finalUrl = await this.uploadToOSS(portraitUrl)
                            uni.hideLoading()
                            this.imgLoading = false
                            resolve(finalUrl)
                        } catch (err) {
                            this.imgLoading = false

                            reject(err)
                        }
                    },
                    fail: (err) => {
                        this.imgLoading = false
                        reject(new Error('获取图片信息失败'))
                    }
                })
            })
        },

        // 压缩图片
        compressImage(filePath) {
            return new Promise((resolve, reject) => {
                uni.getImageInfo({
                    src: filePath,
                    success: (imageInfo) => {
                        // 计算压缩后的尺寸
                        let width = imageInfo.width
                        let height = imageInfo.height

                        if (width > 2400 || height > 2400) {
                            // 计算缩放比例
                            const scale = Math.min(2400 / width, 2400 / height)
                            width = Math.floor(width * scale)
                            height = Math.floor(height * scale)
                        }

                        uni.compressImage({
                            src: filePath,
                            quality: 80,
                            width: width,
                            height: height,
                            success: res => {
                                resolve(res.tempFilePath)
                            },
                            fail: err => {
                                reject(new Error('图片压缩失败'))
                            }
                        })
                    },
                    fail: err => {
                        reject(new Error('获取图片信息失败'))
                    }
                })
            })
        },

        // 上传到OSS
        uploadToOSS(filePath) {
            return new Promise((resolve, reject) => {
                uni.uploadFile({
                    url: 'https://api.liangxibao.com/aliyun/oss/uploadFile',
                    name: 'file',
                    filePath: filePath,
                    header: {
                        Authorization: this.token,
                    },
                    success: (res) => {
                        if (res.statusCode === 200) {
                            try {
                                const data = JSON.parse(res.data)
                                resolve(data.data)
                            } catch (err) {
                                reject(new Error('解析响应数据失败'))
                            }
                        } else {
                            reject(new Error('上传失败'))
                        }
                    },
                    fail: (err) => {
                        reject(err)
                    }
                })
            })
        },

        // 创建证件照
        createPortrait(imageUrl) {
            return new Promise((resolve, reject) => {
                uni.request({
                    url: 'https://jmzjzzz.market.alicloudapi.com/id-phote/create',
                    method: 'POST',
                    header: {
                        'Authorization': 'APPCODE d32de0a30dbe43259c99e394243ff741',
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    data: {
                        url: imageUrl,
                        spec: 'portrait',
                        bgColor: 'white',
                        beautyDegree: 3,
                        size: '295x413',
                        fileSize: '10,30'
                    },
                    success: async (res) => {

                        if (res.data.data && res.data.data.result) {
                            try {
                                // 下载临时链接的图片
                                const tempFilePath = await this.downloadImage(res.data.data.result)
                                resolve(tempFilePath)
                            } catch (err) {
                                reject(new Error('下载证件照失败'))
                            }
                        } else {
                            reject(new Error('生成证件照失败'))
                        }
                    },
                    fail: (err) => {
                        reject(err)
                    }
                })
            })
        },

        // 下载图片
        downloadImage(url) {
            return new Promise((resolve, reject) => {
                uni.downloadFile({
                    url: url,
                    success: (res) => {
                        if (res.statusCode === 200) {
                            resolve(res.tempFilePath)
                        } else {
                            reject(new Error('下载图片失败'))
                        }
                    },
                    fail: (err) => {
                        reject(err)
                    }
                })
            })
        },
        handleSteps() {
            uni.reLaunch({
                url: '/pages/profile/profile'
            })
        },
        handleNext() {
            if (this.portrait_img) {
                uni.showLoading({
                    title: '保存中',
                    mask: true
                })

                const userinfo = uni.getStorageSync('userinfo')
                let params = {
                    avatar: this.portrait_img
                }
                putUserUpdate(params).then(res => {
                    uni.hideLoading()
                    uni.showToast({
                        title: '保存成功',
                        icon: 'success'
                    })
                    // 更新本地存储的用户信息
                    uni.setStorageSync('userinfo', {
                        ...userinfo,
                        avatar: this.portrait_img
                    })
                    if (this.orderId != 'undefined') {
                        uni.showModal({
                            title: '资料提交成功',
                            content: '资料提交成功，老师会在1工作日内联系您',
                            showCancel: false,
                            success: ({ confirm }) => {
                                if (confirm) {
                                    uni.switchTab({ url: '/pages/index/index' })
                                }
                            }
                        })

                    } else {
                        // 返回上一页
                        uni.switchTab({
                            url: '/pages/userInfo/userInfo'
                        })
                    }
                    // uni.navigateBack()
                }).catch(err => {
                    uni.showToast({
                        title: '保存失败',
                        icon: 'error'
                    })
                }).finally(() => {
                    // uni.hideLoading()
                })
            } else {
                uni.showToast({
                    title: '请上传寸照',
                    icon: 'none'
                })
            }
        }
    }
}
</script>

<style lang="scss" scoped>
.portrait {
    margin-top: 20rpx;
    padding-bottom: 168rpx;

    .portrait-steps {
        padding: 30rpx 30rpx;
        border-bottom: 10rpx solid #F7F6F9;
    }

    .portrait-title {
        font-size: 42rpx;
        color: #12141A;
        display: block;
        font-weight: 700;
    }

    .portrait-info {
        font-weight: 400;
        font-size: 26rpx;
        color: #80858F;
        display: block;
        margin-top: 20rpx;
        margin-bottom: 40rpx;
    }

    .portrait-title2 {
        font-weight: 700;
        font-size: 36rpx;
        color: #12141A;
        position: relative;
        margin-bottom: 30rpx;

        &:before {
            content: "";
            position: absolute;
            z-index: -1;
            right: 0;
            bottom: 0;
            background: linear-gradient(90deg, #EDEDED, #FD3523FF);
            border-radius: 2rpx;
            width: 130rpx;
            height: 20rpx;
            opacity: .3;
        }
    }
}

.portrait-card {
    padding: 30rpx;
    border-bottom: 10rpx solid #F7F6F9;
}

.portrait-upload {
    display: flex;
    justify-content: center;
    margin: 50rpx 0;

    .image-wrapper {
        position: relative;
        width: 300rpx;
        height: 400rpx;
        border-radius: 20rpx;
        overflow: hidden;
        background-color: #f5f5f5;

        .portrait-image {
            width: 100%;
            height: 100%;
        }

        .image-actions {
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            display: flex;
            gap: 20rpx;
            transition: opacity 0.3s;

            .action-btn {
                width: 80rpx;
                height: 80rpx;
                background: rgba(0, 0, 0, 0.5);
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;

                .iconfont {
                    color: #fff;
                    font-size: 40rpx;
                }

                &:active {
                    opacity: 0.8;
                }
            }
        }

        &:hover {
            .image-actions {
                opacity: 1;
            }
        }

        &::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.3);
            opacity: 0;
            transition: opacity 0.3s;
        }

        &:hover::before {
            opacity: 1;
        }
    }
}

.portrait-tips {
    margin-top: 40rpx;
    padding: 30rpx;
    background-color: #F7F6F9;
    border-radius: 20rpx;

    .tips-title {
        font-size: 28rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 20rpx;
        display: block;
    }

    .tips-item {
        font-size: 26rpx;
        color: #666;
        display: block;
        margin-bottom: 10rpx;
    }
}

.next-button {
    position: fixed;
    bottom: 40rpx;
    left: 0;
    right: 0;
    padding: 0 30rpx;
    z-index: 100;

    :deep(.uv-button) {
        width: 100%;
        height: 88rpx;
        line-height: 88rpx;
        font-size: 32rpx;
        border-radius: 44rpx;
    }
}
</style>